package com.xuecheng.manage_course.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsPageResult;
import com.xuecheng.framework.domain.cms.response.CmsPostPageResult;
import com.xuecheng.framework.domain.cms.response.CoursePreviewResult;
import com.xuecheng.framework.domain.course.*;
import com.xuecheng.framework.domain.course.ext.CategoryNode;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.CourseView;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.QueryResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_course.client.CmsPageClient;
import com.xuecheng.manage_course.dao.*;
import com.xuecheng.manage_course.service.CourseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Kidy
 * @date 2020/6/26 21:52
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private TeachplanMapper teachplanMapper;

    @Autowired
    private TeachplanRepository teachplanRepository;

    @Autowired
    private TeachplanMediaRepository teachplanMediaRepository;

    @Autowired
    private TeachplanMediaPubRepository teachplanMediaPubRepository;

    @Autowired
    private CourseBaseRepository courseBaseRepository;

    @Autowired
    private CourseMarketRepository courseMarketRepository;

    @Autowired
    private CoursePicRepository coursePicRepository;

    @Autowired
    private CoursePubRepository coursePubRepository;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CmsPageClient cmsPageClient;

    @Value("${course-publish.dataUrlPre}")
    private String publish_dataUrlPre;
    @Value("${course-publish.pagePhysicalPath}")
    private String publish_page_physicalpath;
    @Value("${course-publish.pageWebPath}")
    private String publish_page_webpath;
    @Value("${course-publish.siteId}")
    private String publish_siteId;
    @Value("${course-publish.templateId}")
    private String publish_templateId;
    @Value("${course-publish.previewUrl}")
    private String previewUrl;

    @Override
    public TeachplanNode findTeachplanList(String courseId) {
        return teachplanMapper.selectList(courseId);
    }

    @Override
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {
        if (null == teachplan ||
                StringUtils.isBlank(teachplan.getCourseid()) ||
                StringUtils.isBlank(teachplan.getPname())) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        String courseid = teachplan.getCourseid();
        String parentid = teachplan.getParentid();

        if (StringUtils.isBlank(parentid)) {
            String teachplanRoot = this.getTeachplanRoot(courseid);
            teachplan.setParentid(teachplanRoot);
            teachplan.setGrade("2");
        } else {
            teachplan.setGrade("3");
        }
        teachplan.setId(null);
        teachplanRepository.save(teachplan);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public QueryResponseResult findCourseList(Integer page, Integer size, CourseListRequest courseListRequest) {
        if (null == courseListRequest) {
            courseListRequest = new CourseListRequest();
        }
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 20;
        }
        PageHelper.startPage(page, size);
        Page<CourseInfo> courseListPage = courseMapper.findCourseList(courseListRequest);
        List<CourseInfo> courseList = courseListPage.getResult();
        long total = courseListPage.getTotal();

        QueryResult<CourseInfo> queryResult = new QueryResult();
        queryResult.setList(courseList);
        queryResult.setTotal(total);
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    @Override
    @Transactional
    public ResponseResult addCourseBase(CourseBase courseBase) {
        if (null == courseBase ||
                StringUtils.isBlank(courseBase.getName()) ||
                StringUtils.isBlank(courseBase.getGrade()) ||
                StringUtils.isBlank(courseBase.getStudymodel())) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        courseBase.setStatus("202001");
        courseBase.setId(null);
        courseBaseRepository.save(courseBase);
        return new AddCourseResult(CommonCode.SUCCESS, courseBase.getId());
    }

    @Override
    public CourseBase findCourseBaseById(String id) {
        Optional<CourseBase> optional = courseBaseRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        return optional.get();
    }

    @Override
    @Transactional
    public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        CourseBase save = this.findCourseBaseById(id);
        if (null == this.findCourseBaseById(id)) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        if (null == courseBase ||
                StringUtils.isBlank(courseBase.getName()) ||
                StringUtils.isBlank(courseBase.getGrade()) ||
                StringUtils.isBlank(courseBase.getStudymodel())) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        save.setName(courseBase.getName());
        save.setMt(courseBase.getMt());
        save.setSt(courseBase.getSt());
        save.setGrade(courseBase.getGrade());
        save.setStudymodel(courseBase.getStudymodel());
        save.setUsers(courseBase.getUsers());
        save.setDescription(courseBase.getDescription());
        courseBaseRepository.save(save);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public CourseMarket findCourseMarletById(String id) {
        Optional<CourseMarket> optional = courseMarketRepository.findById(id);
        if (!optional.isPresent()) {
            return null;
        }
        return optional.get();
    }

    @Override
    @Transactional
    public ResponseResult updateCourseMarlet(String id, CourseMarket courseMarket) {
        CourseMarket save = this.findCourseMarletById(id);
        if (null == save) {
            save = new CourseMarket();
            BeanUtils.copyProperties(courseMarket, save);
            save.setId(id);
        } else {
            save.setCharge(courseMarket.getCharge());
            save.setStartTime(courseMarket.getStartTime());
            save.setEndTime(courseMarket.getEndTime());
            save.setQq(courseMarket.getQq());
            save.setValid(courseMarket.getValid());
            save.setPrice(courseMarket.getPrice());
        }
        courseMarketRepository.save(save);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @Transactional
    public ResponseResult addCoursePic(String courseId, String pic) {
        CoursePic coursePic = null;
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (optional.isPresent()) {
            coursePic = optional.get();
        } else {
            coursePic = new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public CoursePic findCoursePic(String courseId) {
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (!optional.isPresent()) {
            return null;
        }
        return optional.get();
    }

    @Override
    @Transactional
    public ResponseResult deleteCoursePic(String courseId) {
        long delete = coursePicRepository.deleteByCourseid(courseId);
        if (delete <= 0) {
            ExceptionCast.cast(CommonCode.FAIL);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public CourseView getCourseView(String id) {
        CourseView courseView = new CourseView();
        //查询课程基本信息
        CourseBase courseBase = this.findCourseBaseById(id);
        if (null != courseBase) {
            courseView.setCourseBase(courseBase);
        }
        //查询课程图片
        CoursePic coursePic = this.findCoursePic(id);
        if (null != coursePic) {
            courseView.setCoursePic(coursePic);
        }
        //查询课程营销
        CourseMarket courseMarket = this.findCourseMarletById(id);
        if (null != courseMarket) {
            courseView.setCourseMarket(courseMarket);
        }
        //查询课程计划
        TeachplanNode teachplanList = this.findTeachplanList(id);
        if (null != teachplanList) {
            courseView.setTeachplanNode(teachplanList);
        }
        return courseView;
    }

    @Override
    public CoursePreviewResult preview(String id) {
        CmsPage cmsPage = new CmsPage();
        CourseBase courseBase = this.findCourseBaseById(id);
        if (null == courseBase) {
            ExceptionCast.cast(CourseCode.COURSE_GET_NOTEXISTS);
        }
        cmsPage.setSiteId(publish_siteId);
        cmsPage.setDataUrl(publish_dataUrlPre + id);
        cmsPage.setPageName(id + ".html");
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setTemplateId(publish_templateId);
        cmsPage.setPageWebPath(publish_page_webpath);
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);

        CmsPageResult cmsPageResult = cmsPageClient.save(cmsPage);
        if (!cmsPageResult.isSuccess()) {
            ExceptionCast.cast(CommonCode.FAIL);
        }
        cmsPage = cmsPageResult.getCmsPage();
        String pageId = cmsPage.getPageId();
        String pageUrl = previewUrl + pageId;
        return new CoursePreviewResult(CommonCode.SUCCESS, pageUrl);
    }

    @Override
    @Transactional
    public CoursePreviewResult publish(String id) {
        CmsPage cmsPage = new CmsPage();
        //查询课程
        //准备页面信息
        CourseBase courseBase = this.findCourseBaseById(id);
        if (null == courseBase) {
            ExceptionCast.cast(CourseCode.COURSE_GET_NOTEXISTS);
        }
        cmsPage.setSiteId(publish_siteId);
        cmsPage.setDataUrl(publish_dataUrlPre + id);
        cmsPage.setPageName(id + ".html");
        cmsPage.setPageAliase(courseBase.getName());
        cmsPage.setTemplateId(publish_templateId);
        cmsPage.setPageWebPath(publish_page_webpath);
        cmsPage.setPagePhysicalPath(publish_page_physicalpath);

        //课程发布
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        if (!cmsPostPageResult.isSuccess()) {
            ExceptionCast.cast(CommonCode.FAIL);
        }

        //更改课程发布状态
        courseBase = this.saveCoursePubState(id);
        if (null == courseBase) {
            ExceptionCast.cast(CommonCode.FAIL);
        }

        //保存课程索引信息
        //...
        CoursePub coursePub = this.createCoursePub(id);
        this.saveCoursePub(id, coursePub);

        this.saveTeachplanMediaPub(id);

        String pageUrl = cmsPostPageResult.getPageUrl();
        return new CoursePreviewResult(CommonCode.SUCCESS, pageUrl);
    }

    @Override
    public ResponseResult saveMedia(TeachplanMedia teachplanMedia) {
        if (null == teachplanMedia || StringUtils.isBlank(teachplanMedia.getTeachplanId())) {
            ExceptionCast.cast(CommonCode.INVALID_PARAM);
        }
        String teachplanId = teachplanMedia.getTeachplanId();
        Optional<Teachplan> optional = teachplanRepository.findById(teachplanId);
        if (!optional.isPresent()) {
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_ISNULL);
        }
        Teachplan teachplan = optional.get();
        if (!StringUtils.equals(teachplan.getGrade(), "3")) {
            ExceptionCast.cast(CourseCode.COURSE_MEDIA_TEACHPLAN_GRADEERROR);
        }
        Optional<TeachplanMedia> teachplanMediaOptional = teachplanMediaRepository.findById(teachplanId);
        TeachplanMedia saveTeachplanMedia = null;
        if (!teachplanMediaOptional.isPresent()) {
            saveTeachplanMedia = new TeachplanMedia();
        } else {
            saveTeachplanMedia = teachplanMediaOptional.get();
        }
        saveTeachplanMedia.setCourseId(teachplan.getCourseid());
        saveTeachplanMedia.setMediaId(teachplanMedia.getMediaId());
        saveTeachplanMedia.setMediaFileOriginalName(teachplanMedia.getMediaFileOriginalName());
        saveTeachplanMedia.setMediaUrl(teachplanMedia.getMediaUrl());
        saveTeachplanMedia.setTeachplanId(teachplanId);

        teachplanMediaRepository.save(saveTeachplanMedia);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    private void saveTeachplanMediaPub(String courseId) {
        //删除数据
        teachplanMediaPubRepository.deleteAllByCourseId(courseId);

        List<TeachplanMedia> teachplanMediaList = teachplanMediaRepository.findAllByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubList = teachplanMediaList.stream().map(teachplanMedia -> {
            TeachplanMediaPub teachplanMediaPub = new TeachplanMediaPub();
            BeanUtils.copyProperties(teachplanMedia, teachplanMediaPub);
            teachplanMediaPub.setTimestamp(new Date());
            return teachplanMediaPub;
        }).collect(Collectors.toList());
        teachplanMediaPubRepository.saveAll(teachplanMediaPubList);
    }

    private CoursePub saveCoursePub(String id, CoursePub coursePub) {
        CoursePub coursePubNew = null;
        Optional<CoursePub> optional = coursePubRepository.findById(id);
        if (!optional.isPresent()) {
            coursePubNew = new CoursePub();
        } else {
            coursePubNew = optional.get();
        }
        BeanUtils.copyProperties(coursePub, coursePubNew);
        coursePubNew.setId(id);
        coursePubNew.setTimestamp(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(new Date());
        coursePubNew.setPubTime(date);
        coursePubRepository.save(coursePubNew);
        return coursePubNew;
    }

    private CoursePub createCoursePub(String id) {
        CoursePub coursePub = new CoursePub();
        //查询课程基本信息
        CourseBase courseBase = this.findCourseBaseById(id);
        if (null != courseBase) {
            BeanUtils.copyProperties(courseBase, coursePub);
        }
        //查询课程图片信息
        CoursePic coursePic = this.findCoursePic(id);
        if (null != coursePic) {
            BeanUtils.copyProperties(coursePic, coursePub);
        }
        //查询课程营销信息
        CourseMarket courseMarket = this.findCourseMarletById(id);
        if (null != courseMarket) {
            BeanUtils.copyProperties(courseMarket, coursePub);
        }
        //查询课程计划信息
        TeachplanNode teachplanNode = this.findTeachplanList(id);
        if (null != teachplanNode) {
            String jsonString = JSON.toJSONString(teachplanNode);
            coursePub.setTeachplan(jsonString);
        }
        return coursePub;
    }

    private CourseBase saveCoursePubState(String courseId) {
        CourseBase courseBase = this.findCourseBaseById(courseId);
        if (null == courseBase) {
            ExceptionCast.cast(CourseCode.COURSE_GET_NOTEXISTS);
        }
        courseBase.setStatus("202002");
        courseBaseRepository.save(courseBase);
        return courseBase;
    }

    private String getTeachplanRoot(String courseid) {
        List<Teachplan> teachplanList = teachplanRepository.findByCourseidAndParentid(courseid, "0");
        if (null == teachplanList || teachplanList.size() <= 0) {
            Optional<CourseBase> optional = courseBaseRepository.findById(courseid);
            if (!optional.isPresent()) {
                return null;
            }
            CourseBase courseBase = optional.get();
            Teachplan teachplan = new Teachplan();
            teachplan.setParentid("0");
            teachplan.setGrade("1");
            teachplan.setPname(courseBase.getName());
            teachplan.setCourseid(courseid);
            teachplan.setStatus("0");
            teachplanRepository.save(teachplan);
            return teachplan.getId();
        }
        return teachplanList.get(0).getId();
    }
}
